<template>
  <div class="createPost-container">

    <sticky :className="'sub-navbar'" :z-index="$upZindex">

      <el-button v-if="opt!='info'" v-loading="loading" style="margin-left: 10px;" type="success" @click="createData">{{$t('table.submit')}}
      </el-button>

      <el-button v-if="opt=='info'" v-loading="loading" style="margin-left: 10px;" type="success" @click="back">{{$t('table.back')}}
    </el-button>

    </sticky>


    <el-form class="form-container" :model="postForm" :rules="rules" ref="postForm" label-position="right" label-width="150px" style='width: 60%; margin-left:10px;margin-top:20px;'>
      <div v-if="opt=='info'">
        <div class="divide-line">作品信息</div>
        <el-form-item label="作品名称" prop="worksName">
          {{postForm.worksName}}
        </el-form-item>

        <el-form-item label="作品类型" prop="worksType">
          {{postForm.worksType | $worksTypeFilter}}
        </el-form-item>

        <el-form-item label="关联ID" prop="copyrightId">
          {{postForm.copyrightId}}
        </el-form-item>
        <div v-if="postForm.worksType=='WorksSingle'">
          <el-form-item label="ISBN号" prop="isbnNo">
            {{postForm.isbnNo}}
          </el-form-item>
          <el-form-item label="出版社" prop="publishingName">
            {{postForm.publishingName}}
          </el-form-item>
          <el-form-item label="文字作者" prop="authorName">
            {{postForm.authorName}}
          </el-form-item>

          <el-form-item label="出版日期" prop="publicationDate">
            {{postForm.publicationDate | $dateConvert}}
          </el-form-item>
        </div>

        <!-- 听书合辑内容 -->
        <div v-if="postForm.worksType=='ListeningCollection'">
          <el-form-item label="主播" prop="anchorName">
            {{postForm.anchorName}}
          </el-form-item>
          <el-form-item label="集数" prop="seriesNum">
            {{postForm.seriesNum}}
          </el-form-item>
          <el-form-item label="定价" prop="worksPrice">
            {{postForm.worksPrice}}
          </el-form-item>
        </div>
        <!-- 听书合辑内容 -->
        <el-form-item label="作品简介" prop="worksIntroduction">
          {{postForm.worksIntroduction}}
        </el-form-item>

        <el-form-item v-if="opt=='info'" label="作品背景" prop="background">
          {{postForm.background | $backgroundFilter}}
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          {{postForm.remark}}
        </el-form-item>
      </div>

      <div class="divide-line">版权信息</div>

      <el-form-item label="版权号" prop="copyrightsNo">
        {{postForm.copyrightsNo}}
      </el-form-item>


      <el-form-item label="合同编号" prop="contractNo">
        {{postForm.contractNo}}
      </el-form-item>

      <el-form-item label="所授权利" prop="copyrightClass">
        <el-tag v-for="(item,index) in postForm.copyrightClass" :key="index">{{item | $copyrightClassFilter}}</el-tag>
      </el-form-item>


      <el-form-item label="是否独家授权" prop="soleFlag">
        {{postForm.soleFlag | $ynFilter}}
      </el-form-item>
      <el-form-item label="有无转授权" prop="subRightsFlag">
        {{postForm.subRightsFlag | $tfFilter}}
      </el-form-item>
      <el-form-item label="有无补协议" prop="protocolFlag">
        {{postForm.protocolFlag | $tfFilter}}
      </el-form-item>

      <el-form-item label="补充协议合同编号" prop="protocolNo">
        {{postForm.protocolNo}}
      </el-form-item>


      <el-form-item label="开始时间" prop="beginDate">
          {{postForm.beginDate | $dateConvert}}
      </el-form-item>
      <el-form-item label="终止时间" prop="endDate">
          {{postForm.endDate | $dateConvert}}
      </el-form-item>
      <el-form-item label="权限使用范围" prop="copyrightsRange">
        <el-tag v-for="(item,index) in postForm.copyrightsRange" :key="index">{{item | $copyrightsRangeFilter}}</el-tag>
      </el-form-item>

      <el-form-item label="使用平台" prop="usedPlatform">
        <el-tag v-for="(item,index) in postForm.usedPlatform" :key="index">{{item | $usedPlatformFilter}}</el-tag>
      </el-form-item>
      <el-form-item label="原始版权" prop="originalCopyrightsFlag">
          {{postForm.originalCopyrightsFlag | $provideFilter}}
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        {{postForm.remark}}
      </el-form-item>


      <div class="divide-line">结算信息</div>

      <el-form-item label="结算形式" prop="balanceType">
        {{postForm.balanceType | $balanceTypeFilter}}
      </el-form-item>


      <el-form-item :label="amountLabelMap[this.postForm.balanceType]" v-if="postForm.balanceType!='DIVIDE'" prop="balance">
        {{postForm.balance}}
      </el-form-item>

      <div v-if="postForm.balanceType!='BUY'">
        <el-form-item label="甲方比例" prop="partyOneNum">
          {{postForm.partyOneNum}}
        </el-form-item>
        <el-form-item label="乙方比例" prop="partyTwoNum">
          {{postForm.partyTwoNum}}
        </el-form-item>
        <el-form-item v-if="postForm.partyThreeNum" label="丙方比例" prop="partyThreeNum">
          {{postForm.partyThreeNum}}
        </el-form-item>
      </div>

      <el-form-item label="结算说明" prop="balanceRemark">
        {{postForm.balanceRemark}}
      </el-form-item>

      <div v-if="opt=='info'">
        <el-form-item label="营业执照/身份证" prop="certNo">
          {{postForm.certNo}}
        </el-form-item>

        <el-form-item label="账户名" prop="accountName">
          {{postForm.accountName}}
        </el-form-item>
        <el-form-item label="开户行" prop="bankName">
          {{postForm.bankName}}
        </el-form-item>
        <el-form-item label="账号" prop="bankNo">
          {{postForm.bankNo}}
        </el-form-item>
      </div>

    </el-form>

    <div v-if="opt=='info'">
      <div class="divide-line-long">合同信息</div>
      <SupplyContractList :contractNo="postForm.contractNo"></SupplyContractList>


      <div v-if="postForm.statis=='VALID'" style="margin-bottom: 30px" align="center">
        <el-button v-has="'contractRightsTable_edit'" type="primary" size="large" @click="handleUpdate">{{$t('table.edit')}}</el-button>
        <el-button v-has="'contractRightsTable_disable'" type="danger" size="large" @click="handleInvalid">{{$t('table.invalid')}}</el-button>
      </div>
    </div>

  </div>

</template>

<script>
  import Sticky from '@/components/Sticky' // 粘性header组件
  import { fetchCopyrightsList, checkCopyrightsDate } from '@/api/copyrights/copyrights'

  import { infoContractRights, createContractRights, updateContractRights, invalidContractRights } from '@/api/contractRights/contractRights'

  import { fetchContractList } from '@/api/supplyContract/supplyContract'

  import SupplyContractList from '@/views/components/SupplyContractList'

  const defaultForm = {
    code: ''
  }

  export default {
    name: 'copyrightAdd',
    components: { Sticky, SupplyContractList },
    data() {
      return {
        postForm: Object.assign({
          balanceType: 'BUY',
          contractType: 'IN',
          contractNum: '2',
          contractNo: '',
          copyrightClass: [],
          copyrightsRange: [],
          usedPlatform: []
        }, defaultForm),
        loading: false,
        rules: {
        },
        listQuery: {
          compoundSearch: undefined,
          expireStatus: undefined,
          clearMethod: undefined,
          contractType: undefined
        },
        copyrightsRangeKeyOptions: ['OVERSEAS', 'MAINLAND', 'GAT'],
        amountLabelMap: {
          BUY: '买断金额',
          PrePayDivide: '预付金额',
          MixClear: '涉及金额',
          DIVIDE: '无金额'
        },
        disabled: false,
        opt: '',
        range_org: {},
        platform_org: {},
        copyrightClass_org: {}
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.content_short.length
      }
    },
    created() {
      const id = this.$route.query.id
      const opt = this.$route.query.opt
      if (id != null) {
        var params = { id: id, opt: opt }
        infoContractRights(params).then(response => {
          if (response.success) {
            this.postForm = Object.assign({}, response.content) // copy obj
            // 权限使用范围选中状态
            const rangestr = response.content.copyrightsRange
            const copyrightsRange = []
            if (rangestr) {
              const ranges = rangestr.split(',')
              for (var range in ranges) {
                copyrightsRange.push(ranges[range])
              }
            }
            this.postForm.copyrightsRange = copyrightsRange
            // 使用平台选中状态
            const platformstr = response.content.usedPlatform
            const usedPlatform = []
            if (platformstr) {
              const platforms = platformstr.split(',')
              for (var platform in platforms) {
                usedPlatform.push(platforms[platform])
              }
            }
            this.postForm.usedPlatform = usedPlatform
            // 所授权利
            const copyrightClassstr = response.content.copyrightClass
            const copyrightClass = []
            if (copyrightClassstr) {
              const copyrightClasses = copyrightClassstr.split(',')
              for (var item in copyrightClasses) {
                copyrightClass.push(copyrightClasses[item])
              }
            }
            this.postForm.copyrightClass = copyrightClass
            // 记录老版权号用于比较
            this.oldCopyrightsNo = this.postForm.copyrightsNo
            this.oldContractNo = this.postForm.contractNo
            // 判断是否是详情页面
            this.opt = this.$route.query.opt
            if (this.opt === 'info') {
              this.disabled = true
              this.range_org = this.postForm.copyrightsRange
              this.platform_org = this.postForm.usedPlatform
              this.copyrightClass_org = this.postForm.copyrightClass
            }
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
            this.$router.go(-1)
          }
        })
      }
    },
    filters: {

    },
    methods: {
      submitForm() {},
      createData() {
        this.$refs['postForm'].validate((valid) => {
          if (valid) {
            const copyrightsRange = this.postForm.copyrightsRange
            const usedPlatform = this.postForm.usedPlatform
            var copyrightsRange_sub = ''
            var usedPlatform_sub = ''
            // 拼接权限使用范围
            for (var i = 0; i < copyrightsRange.length; i++) {
              var item = copyrightsRange[i]
              if (item !== 'true') {
                copyrightsRange_sub += item
                if (i !== copyrightsRange.length - 1) {
                  copyrightsRange_sub += ','
                }
              }
            }
            // 拼接使用平台
            for (var j = 0; j < usedPlatform.length; j++) {
              var item_j = usedPlatform[j]
              if (item_j !== 'true') {
                usedPlatform_sub += item_j
                if (j !== usedPlatform.length - 1) {
                  usedPlatform_sub += ','
                }
              }
            }

            Object.assign(this.postForm, { 'copyrightsRange': copyrightsRange_sub })
            Object.assign(this.postForm, { 'usedPlatform': usedPlatform_sub })

            // 根据是否有id来判断
            if (this.postForm.id != null) {
              updateContractRights(this.postForm).then(response => {
                if (response.success) {
                  this.$notify({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ name: 'contractRightsTable' })
                } else {
                  this.$notify({
                    title: '失败',
                    message: '更新失败',
                    type: 'fail',
                    duration: 2000
                  })
                }
              })
            } else {
              createContractRights(this.postForm).then((response) => {
                if (response.success) {
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ name: 'contractRightsTable' })
                } else {
                  this.$notify({
                    title: '失败',
                    message: '创建失败',
                    type: 'fail',
                    duration: 2000
                  })
                }
              })
            }
            this.postForm.copyrightsRange = copyrightsRange
            this.postForm.usedPlatform = usedPlatform
          }
        })
      },
      // 版权编号选择
      queryCopyrights(queryString, callback) {
        var list = [{}]
        // 调用的后台接口
        // let url = 后台接口地址 + queryString;
        // 从后台获取到对象数组
        const params = { 'copyrightsNo': this.postForm.copyrightsNo }

        fetchCopyrightsList(params).then((response) => {
          if (response.success) {
            // 在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
            for (const i of response.content) {
              // 将名字放入
              Object.assign(i, { 'value': i.copyrightsNo })
            }
            list = response.content
            callback(list)
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 版权选择后的回调
      handleCopyrightsSelect(item) {
        // 校验
        if (item.copyrightsNo == null || item.copyrightsNo === '' || item.copyrightsNo === this.oldCopyrightsNo) {
          return
        }
        const params = { 'copyrightsNo': item.copyrightsNo }
        checkCopyrightsDate(params).then((response) => {
          if (!response.success) {
            this.$message(response.message)
            this.postForm.copyrightsNo = ''
          } else {
            // 赋值
            this.postForm.beginDate = item.beginDate
            this.postForm.endDate = item.endDate
            this.postForm.balanceType = item.balanceType
            this.postForm.balance = item.balance
            this.postForm.partyOne = item.partyOne
            this.postForm.partyOneNum = item.partyOneNum
            this.postForm.partyTwo = item.partyTwo
            this.postForm.partyTwoNum = item.partyTwoNum
            this.postForm.partyThree = item.partyThree
            this.postForm.partyThreeNum = item.partyThreeNum
            this.postForm.balanceRemark = item.balanceRemark
            this.postForm.contractNo = item.contractNo

            this.postForm.copyrightClass = item.copyrightClass
            this.postForm.soleFlag = item.soleFlag
            this.postForm.subRightsFlag = item.subRightsFlag
            this.postForm.protocolFlag = item.protocolFlag
            this.postForm.usedPlatform = item.usedPlatform.split(',')
            this.postForm.copyrightsRange = item.copyrightsRange.split(',')
            this.postForm.originalCopyrightsFlag = item.originalCopyrightsFlag

            this.postForm.copyrightId = item.id
            this.postForm.supplyId = item.supplyId

            this.postForm.contractNum = item.contractNum
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      checkCopyrightsDate() {
        if (this.postForm.copyrightsNo == null || this.postForm.copyrightsNo === '' || this.postForm.copyrightsNo === this.oldCopyrightsNo) {
          return
        }
        const params = { 'copyrightsNo': this.postForm.copyrightsNo }
        checkCopyrightsDate(params).then((response) => {
          if (!response.success) {
            this.$message(response.message)
            this.postForm.copyrightsNo = ''
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 合同编号选择
      queryContractIn(queryString, callback) {
        var list = [{}]
        // 调用的后台接口
        // let url = 后台接口地址 + queryString;
        // 从后台获取到对象数组
        const params = { 'contractNo': this.postForm.contractNo }

        fetchContractList(params).then((response) => {
          if (response.success) {
            // 在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
            for (const i of response.content) {
              // 将名字放入
              Object.assign(i, { 'value': i.contractNo })
            }
            list = response.content
            callback(list)
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 合同选择后的回调
      handleContractSelect(item) {
        // 赋值
        this.postForm.balanceType = item.balanceType
        this.postForm.balance = item.totalAmount
        this.postForm.partyOne = item.partyOne
        this.postForm.partyOneNum = item.partyOneNum
        this.postForm.partyTwo = item.partyTwo
        this.postForm.partyTwoNum = item.partyTwoNum
        this.postForm.partyThree = item.partyThree
        this.postForm.partyThreeNum = item.partyThreeNum
        this.postForm.balanceRemark = item.balanceRemark
        this.postForm.supplyId = item.supplyId
      },
      // 返回
      back() {
        // this.$router.push({ name: 'contractRightsTable' })
        history.go(-1)
      },
      keepOriginCheckBox() {
        if (this.opt === 'info') {
          this.postForm.copyrightsRange = this.range_org
          this.postForm.usedPlatform = this.platform_org
        }
      },
      handleUpdate() {
        this.$router.push({ name: 'contractRightsEdit', query: { id: this.postForm.id }})
      },
      handleInvalid() {
        this.$confirm('失效后，该条数据不可操作，确认失效?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((response) => {
          // 调用失效接口
          var p = { id: this.postForm.id }
          invalidContractRights(p).then(response => {
            if (response.success) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.$router.push({ name: 'contractRightsTable' })
            } else {
              this.$message({
                type: 'fail',
                message: response.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }
    },
    watch: {
      '$route'(to, from) {
        if (from.name === 'contractRightsInfo') {
          this.$router.go(0)
        }
      }
    }
  }
</script>



